package com.enqualcomm.kids.activities;

import android.content.res.TypedArray;
import android.text.Html;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.TerminalDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.heartrate.IHeartRateSettingView;
import com.enqualcomm.kids.mvp.heartrate.Presenter;
import com.enqualcomm.kids.network.socket.response.HeartRateModeQueryResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.dialog.MyToolsTimerPickerDialog2;
import com.enqualcomm.kids.view.heartrate.HeartRateBar;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.Calendar;

import common.utils.PromptUtil;

/**
 * Created by Sunzhigang on 2016/7/18.
 */
@EActivity(R.layout.activity_heart_rate_setting)
public class HeartRateSettingActivity extends BaseActivity implements IHeartRateSettingView {
    int hour = 0;
    int minute = 0;
    @ViewById(R.id.begin_time_tv)
    TextView begin_time_tv;
    @ViewById(R.id.end_time_tv)
    TextView end_time_tv;
    @ViewById(R.id.heart_rate_bar)
    HeartRateBar heart_rate_bar;
    @ViewById(R.id.time_period_tv)
    TextView time_period_tv;
    @ViewById(R.id.auto_rate_switch_iv)
    ImageView auto_rate_switch_iv;
    @ViewById(R.id.title_bar_right_iv)
    ImageView title_bar_right_iv;

    @Extra("terminal")
    TerminallistResult.Terminal terminal;
    HeartRateModeQueryResult.Result settingInfo;
    Presenter presenter;


    int[] rates = {15, 30, 45, 60, 90, 120};//心率频率数组
    int mRate ;
    String beginTimeStr;
    String endTimeStr ;
    boolean isOpen;

    @AfterViews
    void setupViews() {
        presenter = new Presenter(terminal.terminalid);
        presenter.attachSettingView(this);

        UserTerminalDefault userTerminalDefault = new UserTerminalDefault(terminal.userterminalid);
        setupTitleIcon(userTerminalDefault.getInfo(), terminal.terminalid, terminal.userterminalid, "设置");
        TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.bg_save_btn});
        title_bar_right_iv.setImageDrawable(typedArray.getDrawable(0));
        heart_rate_bar.setOnRateOnchangeListener(new HeartRateBar.RateOnchangeListener() {
            @Override
            public void onChange(int position) {
                mRate = rates[position]; //根据位置获取到频率
                showBottomTextView();
            }
        });

        settingInfo = new TerminalDefault(terminal.terminalid).getHeartRateSettings();
        if (settingInfo == null) {
            //赋初始值
            settingInfo = new HeartRateModeQueryResult.Result();
            settingInfo.mode = "15";
            settingInfo.btime =  "00:00";
            settingInfo.etime =  "23:59";
            settingInfo.heartrateopen = "0";
        }
        initView();
        showProgress();
        presenter.queryHeartRateSettings();
    }

    private void initView() {
        mRate = Integer.parseInt(settingInfo.mode);
        beginTimeStr = settingInfo.btime;
        endTimeStr = settingInfo.etime;
        isOpen = "1".equals(settingInfo.heartrateopen);

        heart_rate_bar.setThumberPosition(getBarThumbPosition(mRate));
        begin_time_tv.setText(beginTimeStr);
        end_time_tv.setText(endTimeStr);
        auto_rate_switch_iv.setSelected(isOpen);
        showBottomTextView();
    }

    private int getBarThumbPosition(int rate) {
        for (int i = 0; i < rates.length; i++) {
            if (rates[i]==rate){
                return i;
            }
        }
        return 0;
    }

    @Click(R.id.title_bar_right_iv)
    void saveSettings() {
        settingInfo.btime = beginTimeStr;
        settingInfo.etime = endTimeStr;
        settingInfo.mode = mRate + "";
        settingInfo.heartrateopen = isOpen ? "1" : "0";
        presenter.updateHeartRateSettings(settingInfo);
        showProgress();
    }

    @Click(R.id.title_back_iv)
    void goFinish() {
        finish();
    }


    @Click(R.id.begin_time_tv)
    void setBeginTime() {
        String timeStr = begin_time_tv.getText().toString().trim();
        if (TextUtils.isEmpty(timeStr)) {
            Calendar calendar = Calendar.getInstance();
            hour = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
        } else {
            String[] split = timeStr.split(":");
            hour = Integer.parseInt(split[0]);
            minute = Integer.parseInt(split[1]);
        }

        new MyToolsTimerPickerDialog2(this, new MyToolsTimerPickerDialog2.OnDateTimeSetListener() {
            @Override
            public void onDateTimeSet(int year, int monthOfYear, int dayOfMonth, int hour, int minute) {
                String strHour = "";
                if (hour < 10)
                    strHour = "0" + hour;
                else
                    strHour = "" + hour;

                String strminute = "";
                if (minute < 10)
                    strminute = "0" + minute;
                else
                    strminute = "" + minute;
                beginTimeStr = strHour + ":" + strminute;
                begin_time_tv.setText(beginTimeStr);
                showBottomTextView();
            }
        }, hour, minute).show();

    }


    @Click(R.id.end_time_tv)
    void setEndTime() {
        String timeStr = end_time_tv.getText().toString().trim();
        if (TextUtils.isEmpty(timeStr)) {
            Calendar calendar = Calendar.getInstance();
            hour = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
        } else {
            String[] split = timeStr.split(":");
            hour = Integer.parseInt(split[0]);
            minute = Integer.parseInt(split[1]);
        }

        new MyToolsTimerPickerDialog2(this, new MyToolsTimerPickerDialog2.OnDateTimeSetListener() {
            @Override
            public void onDateTimeSet(int year, int monthOfYear, int dayOfMonth, int hour, int minute) {
                String strHour = "";
                if (hour < 10)
                    strHour = "0" + hour;
                else
                    strHour = "" + hour;

                String strminute = "";
                if (minute < 10)
                    strminute = "0" + minute;
                else
                    strminute = "" + minute;
                endTimeStr = strHour + ":" + strminute;
                end_time_tv.setText(endTimeStr);
                showBottomTextView();
            }
        }, hour, minute).show();
    }

    @Click(R.id.auto_rate_switch_iv)
    void openSwitch() {
        if (isOpen) {
            auto_rate_switch_iv.setSelected(false);
        } else {
            auto_rate_switch_iv.setSelected(true);
        }
        isOpen = !isOpen;
        showBottomTextView();
    }

    private void showBottomTextView() {
        if (isOpen){
            String text = "*" + beginTimeStr + "~" + endTimeStr + ",手表每" + "<font color=\"#ff0000\">" + mRate + "</font>" + "分钟检测一次佩戴者的心率";
            time_period_tv.setText(Html.fromHtml(text));
            time_period_tv.setTextColor(getResources().getColor(R.color.text1));
        }else {
            time_period_tv.setText("*周期检测心率已关闭");
            time_period_tv.setTextColor(getResources().getColor(R.color.text3));
        }
    }

    @Override
    public void updateSettings(HeartRateModeQueryResult.Result result) {
        hideProgress();
        if (result != null) {
            settingInfo = result;
            initView();
        }
    }

    @Override
    public void error() {
        hideProgress();
    }

    @Override
    public void success() {
        hideProgress();
        finish();
//        PromptUtil.toast(this,R.string.set_check_bill_done);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null) {
            presenter.attachSettingView(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        presenter.disAttachSettingView();
    }
}
